<!Doctype html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>Java 对象和类 | 菜鸟教程</title>

  <meta name='robots' content='max-image-preview:large' />
<link rel='stylesheet' id='classic-theme-styles-css' href='../0/classic-themes.min.css?ver=6.2' type='text/css' media='all' />
<link rel="canonical" href="../java/java-object-classes.html" />
<meta name="keywords" content="Java 对象和类">
<meta name="description" content="Java 对象和类 Java作为一种面向对象语言。支持以下基本概念：  	 		多态 	 		继承 	 		封装 	 		抽象 	 		类 	 		对象 	 		实例 	 		方法 	 		重载  本节我们重点研究对象和类的概念。  	 		对象：对象是类的一个实例（对象不是找个女朋友），有状态和行为。例如，一条狗是一个对象，它的状态有：颜色、名字、品种；行为有：摇尾巴、叫、吃等。 	 		类：类是一个模板，它描述一类对象的行为和状态。..">
		
	<link rel="shortcut icon" href="https://static.runoob.com/images/favicon.ico">
	<link rel="stylesheet" href="../0/style.css?v=1.170" type="text/css" media="all" />	
	<link rel="stylesheet" href="../0/font-awesome.min.css" media="all" />	
  <!--[if gte IE 9]><!-->
  <script src=""></script>
  <!--<![endif]-->
  <!--[if lt IE 9]>
     <script src=""></script>
     <script src=""></script>
  <![endif]-->
  <link rel="apple-touch-icon" href="https://static.runoob.com/images/icon/mobile-icon.png"/>
  <meta name="apple-mobile-web-app-title" content="菜鸟教程">
</head>
<body>

<!--  头部 -->
<div class="container logo-search">

  <div class="col search row-search-mobile">
    <form action="index.php">
      <input class="placeholder" placeholder="搜索……" name="s" autocomplete="off">
      
    </form>
  </div>

  <div class="row">
    <div class="col logo">
      <h1><a href="../">菜鸟教程 -- 学的不仅是技术，更是梦想！</a></h1>
    </div>
        <div class="col right-list"> 
    <button class="btn btn-responsive-nav btn-inverse" data-toggle="collapse" data-target=".nav-main-collapse" id="pull" style=""> <i class="fa fa-navicon"></i> </button>
    </div>
        
    <div class="col search search-desktop last">
      <div class="search-input" >
      <form action="//www.runoob.com/" target="_blank">
        <input class="placeholder" id="s" name="s" placeholder="搜索……"  autocomplete="off" style="height: 44px;">
      </form>
      
      </div>
    </div>
  </div>
</div>



<!-- 导航栏 -->
<!-- 导航栏 -->
<div class="container navigation">
	<div class="row">
		<div class="col nav">
			<ul class="pc-nav" id="runoob-detail-nav">
				<li><a href="../">首页</a></li>
				<li><a href="../html/html-tutorial.html">HTML</a></li>
				<li><a href="../css/css-tutorial.html">CSS</a></li>
				<li><a href="../js/js-tutorial.html">JavaScript</a></li>
				<li><a href="javascript:void(0);" data-id="vue">Vue</a></li>
				<li><a href="javascript:void(0);" data-id="bootstrap">Bootstrap</a></li>
				<li><a href="../nodejs/nodejs-tutorial.html">NodeJS</a></li>
				<li><a href="../python3/python3-tutorial.html">Python3</a></li>
				<li><a href="../python/python-tutorial.html">Python2</a></li>
				<li><a href="../java/java-tutorial.html">Java</a></li>
				<li><a href="../cprogramming/c-tutorial.html">C</a></li>
				<li><a href="../cplusplus/cpp-tutorial.html">C++</a></li>
				<li><a href="../csharp/csharp-tutorial.html">C#</a></li>
				<li><a href="../go/go-tutorial.html">Go</a></li>
				<li><a href="../sql/sql-tutorial.html">SQL</a></li>
				<li><a href="../linux/linux-tutorial.html">Linux</a></li>
				<li><a href="../jquery/jquery-tutorial.html">jQuery</a></li>
				<li><a href="../browser-history">本地书签</a></li>
				<!--
			
				<li><a href="../w3cnote/knowledge-start.html" style="font-weight: bold;" onclick="_hmt.push(['_trackEvent', '星球', 'click', 'start'])" title="我的圈子">我的圈子</a></li>				
				<li><a href="javascript:;" class="runoob-pop">登录</a></li>
				-->
      		</ul>
			<ul class="mobile-nav">
				<li><a href="../">首页</a></li>
				<li><a href="../html/html-tutorial.html">HTML</a></li>
				<li><a href="../css/css-tutorial.html">CSS</a></li>
				<li><a href="../js/js-tutorial.html">JS</a></li>
				<li><a href="../browser-history">本地书签</a></li>
				<li><a href="javascript:void(0)" class="search-reveal">Search</a> </li>
			</ul>
			
		</div>
	</div>
</div>

<div class="container sub-navigation sub-navigation-articles" style="display:none">
	<div class="row">
		<div class="col nav-sub">
		<ul id="python">
			<li class="cat-item"><a href="../python3/python3-tutorial.html">Python3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../python/python-tutorial.html">Python2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>
		<ul id="vue">
			<li class="cat-item"><a href="../vue3/vue3-tutorial.html">Vue3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../vue/vue-tutorial.html">vue2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>

		<ul id="bootstrap">
			<li class="cat-item"><a href="../bootstrap/bootstrap-tutorial.html">Bootstrap3 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap4/bootstrap4-tutorial.html">Bootstrap4 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap5/bootstrap5-tutorial.html">Bootstrap5 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
			<li class="cat-item"><a href="../bootstrap/bootstrap-v2-tutorial.html">Bootstrap2 教程 <i class="fa fa-external-link" aria-hidden="true"></i></a></li>
		</ul>
		</div>
	</div>
</div><!--  内容  -->
<div class="container main">
	<!-- 中间 -->
	<div class="row">
	
<div class="runoob-col-md2">
<div class="left-column">
	<div class="tab" style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
	<i class="fa fa-list" aria-hidden="true"></i> 
	<span>Java 教程</span>
	<a data-cate="53" href="javascript:void(0);" title="夜间模式"  id="moon"><i class="fa fa-moon-o" aria-hidden="true" style="line-height: 28px;font-size: 1.2em;margin: 2px 4px 0;"></i></a>
	<a data-cate="53" style="display:none;" href="javascript:void(0);" title="日间模式"  id="sun" ><i class="fa fa-sun-o" aria-hidden="true" style="line-height: 28px;font-size: 1.2em;margin: 2px 4px 0;line-height: 28px;
}"></i></a>

	</div>
	<div class="sidebar-box gallery-list">
		<div class="design" id="leftcolumn">
						<a target="_top" title="Java 教程"  href="../java/java-tutorial.html" >
			Java 教程			</a>
						<a target="_top" title="Java 简介"  href="../java/java-intro.html" >
			Java 简介			</a>
						<a target="_top" title="Java 开发环境配置"  href="../java/java-environment-setup.html" >
			Java 开发环境配置			</a>
						<a target="_top" title="Java 基础语法"  href="../java/java-basic-syntax.html" >
			Java 基础语法			</a>
						<a target="_top" title="Java 对象和类"  href="../java/java-object-classes.html" >
			Java 对象和类			</a>
						<a target="_top" title="Java 基本数据类型"  href="../java/java-basic-datatypes.html" >
			Java 基本数据类型			</a>
						<a target="_top" title="Java 变量类型"  href="../java/java-variable-types.html" >
			Java 变量类型			</a>
						<a target="_top" title="Java 修饰符"  href="../java/java-modifier-types.html" >
			Java 修饰符			</a>
						<a target="_top" title="Java 运算符"  href="../java/java-operators.html" >
			Java 运算符			</a>
						<a target="_top" title="Java 循环结构 &#8211; for, while 及 do&#8230;while"  href="../java/java-loop.html" >
			Java 循环结构			</a>
						<a target="_top" title="Java 条件语句 &#8211; if&#8230;else"  href="../java/java-if-else-switch.html" >
			Java 条件语句			</a>
			<a target="_top" title="Java switch case 语句" href="../java/java-switch-case.html">Java switch case</a>			<a target="_top" title="Java Number &#038; Math 类"  href="../java/java-number.html" >
			Java Number & Math 类			</a>
						<a target="_top" title="Java Character 类"  href="../java/java-character.html" >
			Java Character 类			</a>
						<a target="_top" title="Java String 类"  href="../java/java-string.html" >
			Java String 类			</a>
						<a target="_top" title="Java StringBuffer 和 StringBuilder 类"  href="../java/java-stringbuffer.html" >
			Java StringBuffer			</a>
						<a target="_top" title="Java 数组"  href="../java/java-array.html" >
			Java 数组			</a>
						<a target="_top" title="Java 日期时间"  href="../java/java-date-time.html" >
			Java 日期时间			</a>
						<a target="_top" title="Java 正则表达式"  href="../java/java-regular-expressions.html" >
			Java 正则表达式			</a>
						<a target="_top" title="Java 方法"  href="../java/java-methods.html" >
			Java 方法			</a>
						<a target="_top" title="Java 流(Stream)、文件(File)和IO"  href="../java/java-files-io.html" >
			Java Stream、File、IO			</a>
			<a target="_top" title="Java Scanner 类" href="java-scanner-class.html"> Java Scanner 类 </a>			<a target="_top" title="Java 异常处理"  href="../java/java-exceptions.html" >
			Java 异常处理			</a>
			<br><h2 class="left">Java <span class="left_h2">面向对象</span></h2>			<a target="_top" title="Java 继承"  href="../java/java-inheritance.html" >
			Java 继承			</a>
						<a target="_top" title="Java 重写(Override)与重载(Overload)"  href="../java/java-override-overload.html" >
			Java Override/Overload			</a>
						<a target="_top" title="Java 多态"  href="../java/java-polymorphism.html" >
			Java 多态			</a>
						<a target="_top" title="Java 抽象类"  href="../java/java-abstraction.html" >
			Java 抽象类			</a>
						<a target="_top" title="Java 封装"  href="../java/java-encapsulation.html" >
			Java 封装			</a>
						<a target="_top" title="Java 接口"  href="../java/java-interfaces.html" >
			Java 接口			</a>
			<a target="_top" title="Java 枚举" href="../java/java-enum.html">
			Java 枚举			</a>			<a target="_top" title="Java 包(package)"  href="../java/java-package.html" >
			Java 包(package)			</a>
			<br><h2 class="left">Java <span class="left_h2">高级教程</span></h2>			<a target="_top" title="Java 数据结构"  href="../java/java-data-structures.html" >
			Java 数据结构			</a>
						<a target="_top" title="Java 集合框架"  href="../java/java-collections.html" >
			Java 集合框架			</a>
			<a target="_top" title="Java ArrayList" href="../java/java-arraylist.html">Java ArrayList</a>
<a target="_top" title="Java LinkedList" href="../java/java-linkedlist.html">Java LinkedList</a>
<a target="_top" title="Java HashSet" href="../java/java-hashset.html">Java HashSet</a>
<a target="_top" title="Java  HashMap" href="../java/java-hashmap.html">Java  HashMap</a>
<a target="_top" title="Java  Iterator" href="../java/java-iterator.html">Java  Iterator</a>
<a target="_top" title="Java  Object" href="../java/java-object-class.html">Java  Object</a>			<a target="_top" title="Java 泛型"  href="../java/java-generics.html" >
			Java 泛型			</a>
						<a target="_top" title="Java 序列化"  href="../java/java-serialization.html" >
			Java 序列化			</a>
						<a target="_top" title="Java 网络编程"  href="../java/java-networking.html" >
			Java 网络编程			</a>
						<a target="_top" title="Java 发送邮件"  href="../java/java-sending-email.html" >
			Java 发送邮件			</a>
						<a target="_top" title="Java 多线程编程"  href="../java/java-multithreading.html" >
			Java 多线程编程			</a>
						<a target="_top" title="Java Applet 基础"  href="../java/java-applet-basics.html" >
			Java Applet 基础			</a>
						<a target="_top" title="Java 文档注释"  href="../java/java-documentation.html" >
			Java 文档注释			</a>
						<a target="_top" title="Java 实例"  href="../java/java-examples.html" >
			Java 实例			</a>
						<a target="_top" title="Java 8  新特性"  href="../java/java8-new-features.html" >
			Java 8  新特性			</a>
						<a target="_top" title="Java MySQL 连接"  href="../java/java-mysql-connect.html" >
			Java MySQL 连接			</a>
						<a target="_top" title="Java 9 新特性"  href="../java/java9-new-features.html" >
			Java 9 新特性			</a>
			<a target="_blank" title="Java 测验" href="../quiz/java-quiz.html">Java 测验</a>	
		</div>
	</div>	
</div>
</div>	<div class="col middle-column">
		
	
	<div class="article">
		
		<div class="previous-next-links">
			<div class="previous-design-link"><i style="font-size:16px;" class="fa fa-arrow-left" aria-hidden="true"></i> <a href="../java/java-basic-syntax.html" rel="prev"> Java 基础语法</a> </div>
			<div class="next-design-link"><a href="../java/java-basic-datatypes.html" rel="next"> Java 基本数据类型</a> <i style="font-size:16px;" class="fa fa-arrow-right" aria-hidden="true"></i></div>
		</div>
<div class="article-heading-ad" style="display: block;">
<script async src=""
     crossorigin="anonymous"></script>
<!-- 728*90 固定 -->
<ins class="adsbygoogle"
     style="display:inline-block;width:728px;height:90px"
     data-ad-client="ca-pub-5751451760833794"
     data-ad-slot="2147566827"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
		</div>
		<div class="article-body">
		
			<div class="article-intro" id="content">
			
			<h1>Java 对象和类</h1>
<p>Java作为一种面向对象语言。支持以下基本概念：</p>
<ul>
	<li>
		多态</li>
	<li>
		继承</li>
	<li>
		封装</li>
	<li>
		抽象</li>
	<li>
		类</li>
	<li>
		对象</li>
	<li>
		实例</li>
	<li>
		方法</li>
	<li>
		重载</li>
</ul><p>
本节我们重点研究对象和类的概念。</p>
<ul>
	<li>
		<strong>对象</strong>：对象是类的一个实例（<strong>对象不是找个女朋友</strong>），有状态和行为。例如，一条狗是一个对象，它的状态有：颜色、名字、品种；行为有：摇尾巴、叫、吃等。</li>
	<li>
		<strong>类</strong>：类是一个模板，它描述一类对象的行为和状态。</li>
</ul>
<p>下图中<strong>男孩（boy）</strong>、<strong>女孩（girl）</strong>为<strong>类（class）</strong>，而具体的每个人为该类的<strong>对象（object）</strong>：</p>
<p>
<img decoding="async" src="//www.runoob.com/wp-content/uploads/2013/12/object-class.jpg"></p>
<p>下图中<strong>汽车</strong>为<strong>类（class）</strong>，而具体的每辆车为该<strong>汽车</strong>类的<strong>对象（object）</strong>，对象包含了汽车的颜色、品牌、名称等。</p>
<p><img decoding="async" width="70%" src="https://www.runoob.com/wp-content/uploads/2013/12/class-object2020-10-27.png"></p>
<hr>
<h2>
	Java中的对象</h2>
	<p>
	<p>现在让我们深入了解什么是对象。看看周围真实的世界，会发现身边有很多对象，车，狗，人等等。所有这些对象都有自己的状态和行为。</p>
	<p>拿一条狗来举例，它的状态有：名字、品种、颜色，行为有：叫、摇尾巴和跑。</p>
	<p>对比现实对象和软件对象，它们之间十分相似。</p>
	<p>软件对象也有状态和行为。软件对象的状态就是属性，行为通过方法体现。</p>
	<p>在软件开发中，方法操作对象内部状态的改变，对象的相互调用也是通过方法来完成。</p>
<h2>Java 中的类</h2>
<p>类可以看成是创建 Java 对象的模板。</p>
<p><img decoding="async" src="https://www.runoob.com/wp-content/uploads/2013/12/20210105-java-object-1.png"></p>
<p>通过上图创建一个简单的类来理解下 Java 中类的定义：</p>
<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Dog</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">breed</span><span class="hl-code">;
    </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">size</span><span class="hl-code">;
    </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">colour</span><span class="hl-code">;
    </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">age</span><span class="hl-code">;
 
    </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">eat</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-brackets">}</span><span class="hl-code">
 
    </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">run</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code"> </span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-brackets">}</span><span class="hl-code">
 
    </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">sleep</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-brackets">}</span><span class="hl-code">
 
    </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div>
</div>
<p>一个类可以包含以下类型变量：</p>
<ul>
	<li>
		<strong>局部变量</strong>：在方法、构造方法或者语句块中定义的变量被称为局部变量。变量声明和初始化都是在方法中，方法结束后，变量就会自动销毁。</li>
	<li>
		<strong>成员变量</strong>：成员变量是定义在类中，方法体之外的变量。这种变量在创建对象的时候实例化。成员变量可以被类中方法、构造方法和特定类的语句块访问。</li>
	<li>
		<strong>类变量</strong>：类变量也声明在类中，方法体之外，但必须声明为 static 类型。</li>
</ul>
<p>一个类可以拥有多个方法，在上面的例子中：eat()、run()、sleep() 和 name() 都是 Dog 类的方法。

</p><hr>
<h2>构造方法</h2>
<p>每个类都有构造方法。如果没有显式地为类定义构造方法，Java 编译器将会为该类提供一个默认构造方法。</p>
<p>在创建一个对象的时候，至少要调用一个构造方法。构造方法的名称必须与类同名，一个类可以有多个构造方法。</p>
<p>下面是一个构造方法示例：</p>
<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
    </span><span class="hl-brackets">}</span><span class="hl-code">
 
    </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
        </span><span class="hl-comment">//</span><span class="hl-comment"> 这个构造器仅有一个参数：name</span><span class="hl-comment"></span><span class="hl-code">
    </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div>
</div>
<hr>
<h2>创建对象</h2>
<p>对象是根据类创建的。在Java中，使用关键字 new 来创建一个新的对象。创建对象需要以下三步：</p>
<ul>
	<li>
		<strong>声明</strong>：声明一个对象，包括对象名称和对象类型。</li>
	<li>
		<strong>实例化</strong>：使用关键字 new 来创建一个对象。</li>
	<li>
		<strong>初始化</strong>：使用 new 创建对象时，会调用构造方法初始化对象。</li>
</ul>
<p>下面是一个创建对象的例子：</p>

<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">{</span><span class="hl-code">
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-comment">//</span><span class="hl-comment">这个构造器仅有一个参数：name</span><span class="hl-comment"></span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">小狗的名字是 : </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">name</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">; 
   </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">static</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">main</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-brackets">[</span><span class="hl-brackets">]</span><span class="hl-code"> </span><span class="hl-identifier">args</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-comment">//</span><span class="hl-comment"> 下面的语句将创建一个Puppy对象</span><span class="hl-comment"></span><span class="hl-code">
      </span><span class="hl-identifier">Puppy</span><span class="hl-code"> </span><span class="hl-identifier">myPuppy</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-quotes">&quot;</span><span class="hl-string">tommy</span><span class="hl-quotes">&quot;</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div>
</div>
<p>编译并运行上面的程序，会打印出下面的结果：</p>
<pre>
小狗的名字是 : tommy
</pre>
<hr><h2>
访问实例变量和方法</h2>
<p>

通过已创建的对象来访问成员变量和成员方法，如下所示：</p>
<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-comment">/*</span><span class="hl-comment"> 实例化对象 </span><span class="hl-comment">*/</span><span class="hl-code">
</span><span class="hl-identifier">Object</span><span class="hl-code"> </span><span class="hl-identifier">referenceVariable</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Constructor</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
</span><span class="hl-comment">/*</span><span class="hl-comment"> 访问类中的变量 </span><span class="hl-comment">*/</span><span class="hl-code">
</span><span class="hl-identifier">referenceVariable</span><span class="hl-code">.</span><span class="hl-identifier">variableName</span><span class="hl-code">;
</span><span class="hl-comment">/*</span><span class="hl-comment"> 访问类中的方法 </span><span class="hl-comment">*/</span><span class="hl-code">
</span><span class="hl-identifier">referenceVariable</span><span class="hl-code">.</span><span class="hl-identifier">methodName</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;</span></div>
</div>
</div>
<hr>
<h2>实例</h2><p>

下面的例子展示如何访问实例变量和调用成员方法：</p>
<div class="example">
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">{</span><span class="hl-code">
   </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">puppyAge</span><span class="hl-code">;
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-comment">//</span><span class="hl-comment"> 这个构造器仅有一个参数：name</span><span class="hl-comment"></span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">小狗的名字是 : </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">name</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">; 
   </span><span class="hl-brackets">}</span><span class="hl-code">
 
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">setAge</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">age</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
       </span><span class="hl-identifier">puppyAge</span><span class="hl-code"> = </span><span class="hl-identifier">age</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
 
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">getAge</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
       </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">小狗的年龄为 : </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">puppyAge</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">; 
       </span><span class="hl-reserved">return</span><span class="hl-code"> </span><span class="hl-identifier">puppyAge</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
 
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">static</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">main</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-brackets">[</span><span class="hl-brackets">]</span><span class="hl-code"> </span><span class="hl-identifier">args</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-comment">/*</span><span class="hl-comment"> 创建对象 </span><span class="hl-comment">*/</span><span class="hl-code">
      </span><span class="hl-identifier">Puppy</span><span class="hl-code"> </span><span class="hl-identifier">myPuppy</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Puppy</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-quotes">&quot;</span><span class="hl-string">tommy</span><span class="hl-quotes">&quot;</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-comment">/*</span><span class="hl-comment"> 通过方法来设定age </span><span class="hl-comment">*/</span><span class="hl-code">
      </span><span class="hl-identifier">myPuppy</span><span class="hl-code">.</span><span class="hl-identifier">setAge</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-number">2</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-comment">/*</span><span class="hl-comment"> 调用另一个方法获取age </span><span class="hl-comment">*/</span><span class="hl-code">
      </span><span class="hl-identifier">myPuppy</span><span class="hl-code">.</span><span class="hl-identifier">getAge</span><span class="hl-brackets">(</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-comment">/*</span><span class="hl-comment">你也可以像下面这样访问成员变量 </span><span class="hl-comment">*/</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">变量值 : </span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">myPuppy</span><span class="hl-code">.</span><span class="hl-identifier">puppyAge</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">; 
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div>
</div>

<p>
编译并运行上面的程序，产生如下结果：
</p>
<pre>
小狗的名字是 : tommy
小狗的年龄为 : 2
变量值 : 2
</pre>
<hr>
<h2>源文件声明规则</h2>
<p>在本节的最后部分，我们将学习源文件的声明规则。当在一个源文件中定义多个类，并且还有import语句和package语句时，要特别注意这些规则。</p>
<ul>
	<li>
		一个源文件中只能有一个 public 类</li>
	<li>
		一个源文件可以有多个非 public 类</li>
	<li>
		源文件的名称应该和 public 类的类名保持一致。例如：源文件中 public 类的类名是 Employee，那么源文件应该命名为Employee.java。</li>
	<li>
		如果一个类定义在某个包中，那么 package 语句应该在源文件的首行。</li>
	<li>
		如果源文件包含 import 语句，那么应该放在 package 语句和类定义之间。如果没有 package 语句，那么 import 语句应该在源文件中最前面。</li>
	<li>
		import 语句和 package 语句对源文件中定义的所有类都有效。在同一源文件中，不能给不同的类不同的包声明。</li>
</ul>
<p>类有若干种访问级别，并且类也分不同的类型：抽象类和 final 类等。这些将在访问控制章节介绍。</p>
<p>除了上面提到的几种类型，Java 还有一些特殊的类，如：<a href="../java/java-inner-class.html" rel="noopener noreferrer" target="_blank">内部类</a>、<a href="../java/java-anonymous-class.html" rel="noopener noreferrer" target="_blank">匿名类</a>。</p>
<hr>
<h2>Java 包</h2>
<p>包主要用来对类和接口进行分类。当开发 Java 程序时，可能编写成百上千的类，因此很有必要对类和接口进行分类。</p>
<h2>import 语句</h2>
<p>在 Java 中，如果给出一个完整的限定名，包括包名、类名，那么 Java 编译器就可以很容易地定位到源代码或者类。import 语句就是用来提供一个合理的路径，使得编译器可以找到某个类。</p>
<p>例如，下面的命令行将会命令编译器载入 java_installation/java/io 路径下的所有类</p>
<pre>
import java.io.*;
</pre>
<hr>
<h2>一个简单的例子</h2>
<p>在该例子中，我们创建两个类：<strong>Employee</strong> 和 <strong>EmployeeTest</strong>。</p>
<p>
首先打开文本编辑器，把下面的代码粘贴进去。注意将文件保存为 Employee.java。</p>
<p>
Employee 类有四个成员变量：name、age、designation 和 salary。该类显式声明了一个构造方法，该方法只有一个参数。</p>
<div class="example">
<h2 class="example">Employee.java 文件代码：</h2>
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">import</span><span class="hl-code"> </span><span class="hl-identifier">java</span><span class="hl-code">.</span><span class="hl-identifier">io</span><span class="hl-code">.*;
 
</span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">Employee</span><span class="hl-brackets">{</span><span class="hl-code">
   </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-code">;
   </span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">age</span><span class="hl-code">;
   </span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">designation</span><span class="hl-code">;
   </span><span class="hl-types">double</span><span class="hl-code"> </span><span class="hl-identifier">salary</span><span class="hl-code">;
   </span><span class="hl-comment">//</span><span class="hl-comment"> Employee 类的构造器</span><span class="hl-comment"></span><span class="hl-code">
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-identifier">Employee</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">name</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-reserved">this</span><span class="hl-code">.</span><span class="hl-identifier">name</span><span class="hl-code"> = </span><span class="hl-identifier">name</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-comment">//</span><span class="hl-comment"> 设置age的值</span><span class="hl-comment"></span><span class="hl-code">
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">empAge</span><span class="hl-brackets">(</span><span class="hl-types">int</span><span class="hl-code"> </span><span class="hl-identifier">empAge</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">age</span><span class="hl-code"> =  </span><span class="hl-identifier">empAge</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-comment">/*</span><span class="hl-comment"> 设置designation的值</span><span class="hl-comment">*/</span><span class="hl-code">
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">empDesignation</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-code"> </span><span class="hl-identifier">empDesig</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">designation</span><span class="hl-code"> = </span><span class="hl-identifier">empDesig</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-comment">/*</span><span class="hl-comment"> 设置salary的值</span><span class="hl-comment">*/</span><span class="hl-code">
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">empSalary</span><span class="hl-brackets">(</span><span class="hl-types">double</span><span class="hl-code"> </span><span class="hl-identifier">empSalary</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">salary</span><span class="hl-code"> = </span><span class="hl-identifier">empSalary</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
   </span><span class="hl-comment">/*</span><span class="hl-comment"> 打印信息 </span><span class="hl-comment">*/</span><span class="hl-code">
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">printEmployee</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">名字:</span><span class="hl-quotes">&quot;</span><span class="hl-code">+ </span><span class="hl-identifier">name</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">年龄:</span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">age</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">职位:</span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">designation</span><span class="hl-code"> </span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">System</span><span class="hl-code">.</span><span class="hl-identifier">out</span><span class="hl-code">.</span><span class="hl-identifier">println</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">薪水:</span><span class="hl-quotes">&quot;</span><span class="hl-code"> + </span><span class="hl-identifier">salary</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div>
</div>

<p>程序都是从main方法开始执行。为了能运行这个程序，必须包含main方法并且创建一个实例对象。</p>

<p>下面给出EmployeeTest类，该类实例化2个 Employee 类的实例，并调用方法设置变量的值。</p>

<p>将下面的代码保存在 EmployeeTest.java文件中。</p>
<div class="example">
<h2 class="example">EmployeeTest.java 文件代码：</h2>
<div class="example_code">
<div class="hl-main"><span class="hl-reserved">import</span><span class="hl-code"> </span><span class="hl-identifier">java</span><span class="hl-code">.</span><span class="hl-identifier">io</span><span class="hl-code">.*;
</span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-reserved">class</span><span class="hl-code"> </span><span class="hl-identifier">EmployeeTest</span><span class="hl-brackets">{</span><span class="hl-code">
 
   </span><span class="hl-reserved">public</span><span class="hl-code"> </span><span class="hl-types">static</span><span class="hl-code"> </span><span class="hl-types">void</span><span class="hl-code"> </span><span class="hl-identifier">main</span><span class="hl-brackets">(</span><span class="hl-identifier">String</span><span class="hl-brackets">[</span><span class="hl-brackets">]</span><span class="hl-code"> </span><span class="hl-identifier">args</span><span class="hl-brackets">)</span><span class="hl-brackets">{</span><span class="hl-code">
      </span><span class="hl-comment">/*</span><span class="hl-comment"> 使用构造器创建两个对象 </span><span class="hl-comment">*/</span><span class="hl-code">
      </span><span class="hl-identifier">Employee</span><span class="hl-code"> </span><span class="hl-identifier">empOne</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Employee</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">RUNOOB1</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">Employee</span><span class="hl-code"> </span><span class="hl-identifier">empTwo</span><span class="hl-code"> = </span><span class="hl-reserved">new</span><span class="hl-code"> </span><span class="hl-identifier">Employee</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">RUNOOB2</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
 
      </span><span class="hl-comment">//</span><span class="hl-comment"> 调用这两个对象的成员方法</span><span class="hl-comment"></span><span class="hl-code">
      </span><span class="hl-identifier">empOne</span><span class="hl-code">.</span><span class="hl-identifier">empAge</span><span class="hl-brackets">(</span><span class="hl-number">26</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">empOne</span><span class="hl-code">.</span><span class="hl-identifier">empDesignation</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">高级程序员</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">empOne</span><span class="hl-code">.</span><span class="hl-identifier">empSalary</span><span class="hl-brackets">(</span><span class="hl-number">1000</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">empOne</span><span class="hl-code">.</span><span class="hl-identifier">printEmployee</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
 
      </span><span class="hl-identifier">empTwo</span><span class="hl-code">.</span><span class="hl-identifier">empAge</span><span class="hl-brackets">(</span><span class="hl-number">21</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">empTwo</span><span class="hl-code">.</span><span class="hl-identifier">empDesignation</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">菜鸟程序员</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">empTwo</span><span class="hl-code">.</span><span class="hl-identifier">empSalary</span><span class="hl-brackets">(</span><span class="hl-number">500</span><span class="hl-brackets">)</span><span class="hl-code">;
      </span><span class="hl-identifier">empTwo</span><span class="hl-code">.</span><span class="hl-identifier">printEmployee</span><span class="hl-brackets">(</span><span class="hl-brackets">)</span><span class="hl-code">;
   </span><span class="hl-brackets">}</span><span class="hl-code">
</span><span class="hl-brackets">}</span></div>
</div>
</div>
<p>编译这两个文件并且运行 EmployeeTest 类，可以看到如下结果：</p>
<pre>
$ javac EmployeeTest.java
$ java EmployeeTest 
名字:RUNOOB1
年龄:26
职位:高级程序员
薪水:1000.0
名字:RUNOOB2
年龄:21
职位:菜鸟程序员
薪水:500.0
</pre>
			<!-- 其他扩展 -->
						
			</div>
			
		</div>
		
		<div class="previous-next-links">
			<div class="previous-design-link"><i style="font-size:16px;" class="fa fa-arrow-left" aria-hidden="true"></i> <a href="../java/java-basic-syntax.html" rel="prev"> Java 基础语法</a> </div>
			<div class="next-design-link"><a href="../java/java-basic-datatypes.html" rel="next"> Java 基本数据类型</a> <i style="font-size:16px;" class="fa fa-arrow-right" aria-hidden="true"></i></div>
		</div>
		<!-- 笔记列表 -->
		<style>
.wrapper {
  /*text-transform: uppercase; */
  background: #ececec;
  color: #555;
  cursor: help;
  font-family: "Gill Sans", Impact, sans-serif;
  font-size: 20px;
  position: relative;
  text-align: center;
  width: 200px;
  -webkit-transform: translateZ(0); /* webkit flicker fix */
  -webkit-font-smoothing: antialiased; /* webkit text rendering fix */
}

.wrapper .tooltip {
  white-space: nowrap;
  font-size: 14px;
  text-align: left;
  background: #96b97d;
  bottom: 100%;
  color: #fff;
  display: block;
  left: -25px;
  margin-bottom: 15px;
  opacity: 0;
  padding: 14px;
  pointer-events: none;
  position: absolute;
  
  -webkit-transform: translateY(10px);
     -moz-transform: translateY(10px);
      -ms-transform: translateY(10px);
       -o-transform: translateY(10px);
          transform: translateY(10px);
  -webkit-transition: all .25s ease-out;
     -moz-transition: all .25s ease-out;
      -ms-transition: all .25s ease-out;
       -o-transition: all .25s ease-out;
          transition: all .25s ease-out;
  -webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
     -moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      -ms-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
       -o-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
          box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}
.tooltip a {
	color:#fff;
}
/* This bridges the gap so you can mouse into the tooltip without it disappearing */
.wrapper .tooltip:before {
  bottom: -20px;
  content: " ";
  display: block;
  height: 20px;
  left: 0;
  position: absolute;
  width: 100%;
}  

/* CSS Triangles - see Trevor's post */
.wrapper .tooltip:after {
  border-left: solid transparent 10px;
  border-right: solid transparent 10px;
  border-top: solid #96b97d 10px;
  bottom: -10px;
  content: " ";
  height: 0;
  left: 20%;
  margin-left: -13px;
  position: absolute;
  width: 0;
}
.wrapper .tooltip1 {
	margin-left: 50px;
	padding-top: 0px;
}
/*
.wrapper:hover .tooltip {
  opacity: 1;
  pointer-events: auto;
  -webkit-transform: translateY(0px);
     -moz-transform: translateY(0px);
      -ms-transform: translateY(0px);
       -o-transform: translateY(0px);
          transform: translateY(0px);
}
*/
/* IE can just show/hide with no transition */
.lte8 .wrapper .tooltip {
  display: none;
}

.lte8 .wrapper:hover .tooltip {
  display: block;
}

</style>

<link rel="stylesheet" href="../0/upvotejs.css">
<script src=""></script>
<script src=""></script>
<div class="title" id="comments">
	<h2 class="">
    <div class="altblock">
				<i style="font-size:28px;margin-top: 8px;" class="fa fa-plus-square" aria-hidden="true"></i>
		    </div>
    <span class="mw-headline" id="qa_headline">15  篇笔记</span>
	<span class="mw-headline" id="user_add_note" style="float:right;line-height: 62px;padding-right: 14px;"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>  写笔记</span>
    </h2>
</div>

<div id="postcomments"  style="display:none;" >
	<ol class="commentlist">
		<li class="comment even thread-even depth-1" id="comment-11759"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;stinkaroo</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;190***276@qq.com</p></div><div id="runoobvote-id-11759" data-commid = "11759" class="upvotejs"><a class="upvote"></a> <span class="count">551</span></div></div><div class="comt-main" id="div-comment-11759"><p>java因强制要求类名（唯一的public类）和文件名统一，因此在引用其它类时无需显式声明。在编译时，编译器会根据类名去寻找同名文件。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">stinkaroo</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;stinkaroo</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;190***276@qq.com</p></div></span>6年前 (2017-05-08)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-15722"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;LadyLeane</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;q-b***sn.com</p></div><div id="runoobvote-id-15722" data-commid = "15722" class="upvotejs"><a class="upvote"></a> <span class="count">305</span></div></div><div class="comt-main" id="div-comment-15722"><p data-title="Java package 的作用">package 的作用就是 c++ 的 namespace 的作用，防止名字相同的类产生冲突。Java 编译器在编译时，直接根据 package 指定的信息直接将生成的 class 文件生成到对应目录下。如 <span class="marked">package aaa.bbb.ccc</span> 编译器就将该 .java 文件下的各个类生成到 <span class="marked">./aaa/bbb/ccc/</span> 这个目录。</p>

<p>import 是为了简化使用 package 之后的实例化的代码。假设 <span class="marked">./aaa/bbb/ccc/</span> 下的 A 类，假如没有 import，实例化A类为：<span class="marked">new aaa.bbb.ccc.A()</span>，使用 <span class="marked">import aaa.bbb.ccc.A</span> 后，就可以直接使用 <span class="marked">new A()</span> 了，也就是编译器匹配并扩展了 <span class="marked">aaa.bbb.ccc.</span> 这串字符串。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/15722">LadyLeane</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;LadyLeane</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;q-b***sn.com</p></div></span>6年前 (2017-08-02)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-17611"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;阿弥托福哦</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;253***7490@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="http://wenda.so.com/q/1378788045066449">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-17611" data-commid = "17611" class="upvotejs"><a class="upvote"></a> <span class="count">208</span></div></div><div class="comt-main" id="div-comment-17611"><p data-title="为什么 JAVA 文件中只能含有一个 Public 类?"><strong>为什么JAVA文件中只能含有一个Public类?</strong></p>
<p>java 程序是从一个 public 类的 main 函数开始执行的，(其实是main线程)，就像 C 程序 是从 main() 函数开始执行一样。 只能有一个
 public 类是为了给类装载器提供方便。 一个 public 类只能定义在以它的类名为文件名的文件中。 </p><p>每个编译单元(文件)都只有一个 public 类。因为每个编译单元都只能有一个公共接口，用 public 类来表现。该接口可以按照要求包含众多的支持包访问权限的类。如果有一个以上的 public 类，编译器就会报错。 并且 public类的名称必须与文件名相同(严格区分大小写)。 当然一个编译单元内也可以没有 public 类。 </p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/17611">阿弥托福哦</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;阿弥托福哦</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;253***7490@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="http://wenda.so.com/q/1378788045066449">&nbsp;&nbsp;参考地址</a></p></div></span>6年前 (2017-09-15)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-18216"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;pxn626</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;790***000@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="http://blog.csdn.net/du_minchao/article/details/48881637">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-18216" data-commid = "18216" class="upvotejs"><a class="upvote"></a> <span class="count">534</span></div></div><div class="comt-main" id="div-comment-18216"><p data-title="Java 成员变量和类变量的区别" data-commid="20302,26234"><strong>成员变量和类变量的区别</strong></p><p></p><p></p><p>由static修饰的变量称为静态变量，其实质上就是一个全局变量。如果某个内容是被所有对象所共享，那么该内容就应该用静态修饰；没有被静态修饰的内容，其实是属于对象的特殊描述。</p><p>不同的对象的实例变量将被分配不同的内存空间， 如果类中的成员变量有类变量，那么所有对象的这个类变量都分配给相同的一处内存，改变其中一个对象的这个类变量会影响其他对象的这个类变量，也就是说对象共享类变量。</p><p>成员变量和类变量的区别：</p><p>&nbsp;&nbsp; 1、两个变量的生命周期不同</p><p>&nbsp; &nbsp;&nbsp;&nbsp; 成员变量随着对象的创建而存在，随着对象的回收而释放。</p><p>&nbsp; &nbsp; &nbsp; 静态变量随着类的加载而存在，随着类的消失而消失。</p><p>&nbsp;&nbsp; 2、调用方式不同</p><p>&nbsp; &nbsp; &nbsp; 成员变量只能被对象调用。</p><p>&nbsp; &nbsp; &nbsp; 静态变量可以被对象调用，还可以被类名调用。</p><p>&nbsp;&nbsp; 3、别名不同</p><p>&nbsp; &nbsp;&nbsp;&nbsp; 成员变量也称为实例变量。</p><p>&nbsp; &nbsp; &nbsp; 静态变量也称为类变量。</p><p>&nbsp;&nbsp; 4、数据存储位置不同</p><p>&nbsp; &nbsp; &nbsp; 成员变量存储在堆内存的对象中，所以也叫对象的特有数据。</p><p>&nbsp; &nbsp; &nbsp; 静态变量数据存储在方法区（共享数据区）的静态区，所以也叫对象的共享数据。</p><p></p><p></p><p>static 关键字，是一个修饰符，用于修饰成员(成员变量和成员函数)。</p><p>&nbsp;&nbsp; 特点：</p><p>&nbsp;&nbsp; 1、想要实现对象中的共性数据的对象共享。可以将这个数据进行静态修饰。</p><p>&nbsp;&nbsp; 2、被静态修饰的成员，可以直接被类名所调用。也就是说，静态的成员多了一种调用方式。类名.静态方式。</p><p>&nbsp;&nbsp;&nbsp; 3、静态随着类的加载而加载。而且优先于对象存在。</p><p>&nbsp;</p><p>弊端：</p><p>&nbsp;&nbsp; 1、有些数据是对象特有的数据，是不可以被静态修饰的。因为那样的话，特有数据会变成对象的共享数据。这样对事物的描述就出了问题。所以，在定义静态时，必须要明确，这个数据是否是被对象所共享的。</p><p>&nbsp;&nbsp; 2、静态方法只能访问静态成员，不可以访问非静态成员。</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 因为静态方法加载时，优先于对象存在，所以没有办法访问对象中的成员。</p><p>&nbsp;&nbsp; 3、静态方法中不能使用this，super关键字。</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 因为this代表对象，而静态在时，有可能没有对象，所以this无法使用。</p><p>&nbsp;</p><p>什么时候定义静态成员呢？或者说：定义成员时，到底需不需要被静态修饰呢？</p><p>成员分两种：</p><p>&nbsp;&nbsp; 1、成员变量。（数据共享时静态化）</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 该成员变量的数据是否是所有对象都一样：</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果是，那么该变量需要被静态修饰，因为是共享的数据。&nbsp;</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果不是，那么就说这是对象的特有数据，要存储到对象中。&nbsp;</p><p>&nbsp;&nbsp; 2、成员函数。（方法中没有调用特有数据时就定义成静态）</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果判断成员函数是否需要被静态修饰呢？</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 只要参考，该函数内是否访问了对象中的特有数据：</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果有访问特有数据，那方法不能被静态修饰。</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 如果没有访问过特有数据，那么这个方法需要被静态修饰。</p><p></p><p>成员变量和静态变量的区别：</p><p>&nbsp;&nbsp; 1、成员变量所属于对象。所以也称为实例变量。</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 静态变量所属于类。所以也称为类变量。</p><p>&nbsp;&nbsp; 2、成员变量存在于堆内存中。</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 静态变量存在于方法区中。</p><p>&nbsp;&nbsp; 3、成员变量随着对象创建而存在。随着对象被回收而消失。</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 静态变量随着类的加载而存在。随着类的消失而消失。</p><p>&nbsp;&nbsp; 4、成员变量只能被对象所调用&nbsp;。</p><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 静态变量可以被对象调用，也可以被类名调用。</p><p>&nbsp;&nbsp; 所以，成员变量可以称为对象的特有数据，静态变量称为对象的共享数据。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/18216">pxn626</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;pxn626</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;790***000@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="http://blog.csdn.net/du_minchao/article/details/48881637">&nbsp;&nbsp;参考地址</a></p></div></span>6年前 (2017-09-28)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-20302"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Demetris</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;150***67161@163.com</p></div><div id="runoobvote-id-20302" data-commid = "20302" class="upvotejs"><a class="upvote"></a> <span class="count">187</span></div></div><div class="comt-main" id="div-comment-20302"><p><strong>类变量类型：</strong></p>

<p>1.局部变量：在方法、构造方法、语句块中定义的变量。其声明和初始化在方法中实现，在方法结束后自动销毁</p>

<pre>public class  ClassName{
    public void printNumber（）{
        int a;
    }
    // 其他代码
}</pre>

<p>2.成员变量：定义在类中，方法体之外。变量在创建对象时实例化。成员变量可被类中的方法、构造方法以及特定类的语句块访问。</p>

<pre>public class  ClassName{
    int a;
    public void printNumber（）{
        // 其他代码
    }
}</pre>

<p>3.类变量：定义在类中，方法体之外，但必须要有 static 来声明变量类型。静态成员属于整个类，可通过对象名或类名来调用。</p>

<pre>public class  ClassName{
    static int a;
    public void printNumber（）{
        // 其他代码
    }
}</pre>

<div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">Demetris</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Demetris</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;150***67161@163.com</p></div></span>6年前 (2017-11-14)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-23594"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;ycxchkj</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;xch***163.com</p></div><div id="runoobvote-id-23594" data-commid = "23594" class="upvotejs"><a class="upvote"></a> <span class="count">102</span></div></div><div class="comt-main" id="div-comment-23594"><p><strong>类的构造方法</strong></p><p>1、构造方法的名字和类名相同，并且没有返回值。</p><p>2、构造方法主要用于为类的对象定义初始化状态。</p><p>3、我们不能直接调用构造方法，必须通过new关键字来自动调用，从而创建类的实例。</p><p>4、Java的类都要求有构造方法，如果没有定义构造方法，Java编译器会为我们提供一个缺省的构造方法，也就是不带参数的构造方法。</p><p><strong>new关键字的作用</strong></p><p>1、为对象分配内存空间。</p><p>2、引起对象构造方法的调用。</p><p>3、为对象返回一个引用。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">ycxchkj</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;ycxchkj</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;xch***163.com</p></div></span>5年前 (2018-01-27)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-25167"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Lynn</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;276***577@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-25167" data-commid = "25167" class="upvotejs"><a class="upvote"></a> <span class="count">37</span></div></div><div class="comt-main" id="div-comment-25167">

<blockquote><p><strong>Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object.</strong></p></blockquote>



<p>以上是 Oracle 对于静态的定义。大意为，有时候，你想拥有所有对象通用的变量。 这是通过静态修改器完成的。 在其声明中具有静态修饰符的字段称为静态字段或类变量。 他们与类相关，而不是与任何对象相关联。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">Lynn</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Lynn</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;276***577@qq.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html">&nbsp;&nbsp;参考地址</a></p></div></span>5年前 (2018-03-18)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-25742"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;lllunaticer</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;tdl***tju.edu.cn</p></div><div id="runoobvote-id-25742" data-commid = "25742" class="upvotejs"><a class="upvote"></a> <span class="count">69</span></div></div><div class="comt-main" id="div-comment-25742"><p>使用java类实例化一个对象的时候，如果在类中不显式的声明其构造函数，则会使用一个默认的构造函数来初始化对象。</p>

<p>实例：</p>

<pre>//一个没有显式声明构造函数的类
Public class People{
    int age = 23;
    Public void getAge(){
        System.out.print("the age is "+age);
    }
}

//用这个类来实例化一个对象
People xiaoMing = new People(); // People() 是People类的默认构造函数，它什么也不干
xiaoMing.getAge();//打印年龄</pre>

<p>也可以在声明类的时候显式的声明一个构造函数：</p>

<pre>//一个带显式构造函数的类
Public class People{
    int age = 23;
        Public void getAge(){
        System.out.print("the age is "+ age);
    }
    // 显式声明一个带参数的构造函数，用于初始化年龄
    Public People(int a){
        this.age = a; 
    }
}

//用这个类来实例化一个对象
People xiaoMing = new People(20); // 使用带参数的构造函数来实例化对象
xiaoMing.getAge(); // 打印出来的年龄变为20</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">lllunaticer</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;lllunaticer</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;tdl***tju.edu.cn</p></div></span>5年前 (2018-03-31)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-26234"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;2333</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;135***8036@qq.com</p></div><div id="runoobvote-id-26234" data-commid = "26234" class="upvotejs"><a class="upvote"></a> <span class="count">65</span></div></div><div class="comt-main" id="div-comment-26234"><h2>成员变量和局部变量区别
</h2>
<p><strong>1.声明位置不同</strong></p>

<p>成员变量也就是属性，在类中声明的。</p>

<p>局部变量，在方法中声明或代码块中声明。</p>

<p><strong>2.初始值不同</strong></p>

<p>成员变量如果没有赋值则是有默认值的，数据类型不同则默认值不同。</p>

<p>局部变量是没有默认值，也就是说必须先声明，再赋值，最后才使用。</p>

<p><strong>3.在一个类中，局部变量可以与成员变量同名，但是局部变量优先,如果非要访问成员变量的属性，则必须使用 this.color</strong></p>

<p><span class="marked">this</span> 代表当前这个对象，也就是当前谁调用这个方法则这个对象就是谁。</p>

<h2>对象与引用区别
</h2>
<p>对象是具体的一个实例，如：<span class="marked">new Student();</span> new 表示创建一个对象，并在堆内存中开辟一块空间。</p>

<p>引用名称是存放的对象的地址。</p>

<div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">2333</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;2333</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;135***8036@qq.com</p></div></span>5年前 (2018-04-13)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-26436"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;tfbyly</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;905***717@qq.com</p></div><div id="runoobvote-id-26436" data-commid = "26436" class="upvotejs"><a class="upvote"></a> <span class="count">85</span></div></div><div class="comt-main" id="div-comment-26436"><p><strong>内部类</strong>：将一个类的定义放在另一个类的定义内部，这就是内部类。</p>

<p>如同一个人是由大脑、肢体、器官等身体结果组成，而内部类相当于其中的某个器官之一，例如心脏：它也有自己的属性和行为（血液、跳动）</p>

<p>显然，此处不能单方面用属性或者方法表示一个心脏，而需要一个类，而心脏又在人体当中，正如同是内部类在外部类当中。</p>

<p>1）不用内部类：</p>

<pre>public class Person {
    private int blood;
    private Heart heart;
}

public class Heart {
    private int blood;
    public void test() {
        System.out.println(blood);
    }
}</pre>

<p>2）使用内部类：</p>


<pre>public class Person {
    private int blood;
    public class Heart {
        public void test() {
            System.out.println(blood);
        }
    }

    public class Brain {
        public void test() {
            System.out.println(blood);
        }
    }
}</pre>


<p><strong>内部类优点和缺点：</strong></p>
<ul><li>
优点：可访问外部类私有属性（心脏可访问身体的血液，而不是外部抽血）。
</li><li>
缺点：破坏原有类的程序结构（属性、构造方法、普通方法、内部类）。
</li></ul>
<p><strong>应用举例</strong></p>
<pre>//外部类
class Out {
    private int age = 12;
     
    //内部类
    class In {
        public void print() {
            System.out.println(age);
        }
    }
}
 
public class Demo {
    public static void main(String[] args) {
        Out.In in = new Out().new In();
        in.print();
        //或者采用下种方式访问
        /*
        Out out = new Out();
        Out.In in = out.new In();
        in.print();
        */
    }
}</pre>

<p>运行结果：12</p>

<p>从上面的例子不难看出，内部类其实严重破坏了良好的代码结构，但为什么还要使用内部类呢？</p>

<p>因为内部类可以随意使用外部类的成员变量（包括私有）而不用生成外部类的对象，这也是内部类的唯一优点。</p>

<p>如同心脏可以直接访问身体的血液，而不是通过医生来抽血。</p>

 

<p>程序编译过后会产生两个 .class 文件，分别是 Out.class 和 Out$In.class。</p>

<p>其中 $ 代表了上面程序中 Out.In 中的那个。</p>

<p><span class="marked">Out.In in = new Out().new In()</span> 可以用来生成内部类的对象，这种方法存在两个小知识点需要注意：</p>
<ul><li>
1.开头的 Out 是为了标明需要生成的内部类对象在哪个外部类当中。
</li><li>
2.必须先有外部类的对象才能生成内部类的对象，因为内部类的作用就是为了访问外部类中的成员变量。</li></ul>
<h3>实例2：内部类中的变量访问形式</h3>
<p><strong>更多详细内容可参考：</strong></p>
<p><a href="../w3cnote/java-inner-class-summary.html" target="_blank" rel="noopener nofollow">java 中的内部类总结</a></p><a href="../w3cnote/java-inner-class-intro.html" target="_blank" rel="noopener nofollow">Java 内部类详解</a>

<div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">tfbyly</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;tfbyly</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;905***717@qq.com</p></div></span>5年前 (2018-04-18)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-29207"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;小宝呼呼</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;hua***aoling66@163.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="../w3cnote/the-different-this-super.html">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-29207" data-commid = "29207" class="upvotejs"><a class="upvote"></a> <span class="count">55</span></div></div><div class="comt-main" id="div-comment-29207"><p>更多内容参考：<a href="../w3cnote/the-different-this-super.html" target="_blank" rel="noopener nofollow">Java 中 this 和 super 的用法总结</a>。</p>
<ul><li>
<span class="marked">this</span> 指向对象本身的指针，形参与成员名字重名，用 this 来区分。
</li><li>
<span class="marked">super</span> 超（父）类对象的一个指针。</li></ul>
<p>对构造函数对引用：</p>

<pre>class Person { 
    public static void prt(String s) { 
       System.out.println(s); 
    } 
   
    Person() { 
       prt("父类&middot;无参数构造方法： "+"A Person."); 
    }//构造方法(1) 
    
    Person(String name) { 
       prt("父类&middot;含一个参数的构造方法： "+"A person's name is " + name); 
    }//构造方法(2) 
} 
    
public class Chinese extends Person { 
    Chinese() { 
       super(); // 调用父类构造方法（1） 
       prt("子类&middot;调用父类&rdquo;无参数构造方法&ldquo;： "+"A chinese coder."); 
    } 
    
    Chinese(String name) { 
       super(name);// 调用父类具有相同形参的构造方法（2） 
       prt("子类&middot;调用父类&rdquo;含一个参数的构造方法&ldquo;： "+"his name is " + name); 
    } 
    
    Chinese(String name, int age) { 
       this(name);// 调用具有相同形参的构造方法（3） 
       prt("子类：调用子类具有相同形参的构造方法：his age is " + age); 
    } 
    
    public static void main(String[] args) { 
       Chinese cn = new Chinese(); 
       cn = new Chinese("codersai"); 
       cn = new Chinese("codersai", 18); 
    } 
}</pre>
<p>运行结果：</p>
<pre>父类&middot;无参数构造方法： A Person.
子类&middot;调用父类&rdquo;无参数构造方法&ldquo;： A chinese coder.
父类&middot;含一个参数的构造方法： A person's name is codersai
子类&middot;调用父类&rdquo;含一个参数的构造方法&ldquo;： his name is codersai
父类&middot;含一个参数的构造方法： A person's name is codersai
子类&middot;调用父类&rdquo;含一个参数的构造方法&ldquo;： his name is codersai
子类：调用子类具有相同形参的构造方法：his age is 18</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">小宝呼呼</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;小宝呼呼</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;hua***aoling66@163.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="../w3cnote/the-different-this-super.html">&nbsp;&nbsp;参考地址</a></p></div></span>5年前 (2018-07-06)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-34937"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;samcyang</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;532***194@qq.com</p></div><div id="runoobvote-id-34937" data-commid = "34937" class="upvotejs"><a class="upvote"></a> <span class="count">25</span></div></div><div class="comt-main" id="div-comment-34937"><p>JAVA 和 C++ 一样，若是不定义任何的构造函数，会自动构造；如果定义了任何一个构造函数，就不会再自动构造，需要自己定义全部的构造函数。</p>

<pre>//一个带显式构造函数的类
Public class People{
    int age = 23;
        Public void getAge(){
        System.out.print("the age is "+ age);
    }
    // 显式声明一个带参数的构造函数，用于初始化年龄
    Public People(int a){
        this.age = a; 
    }
}

//用这个类来实例化一个对象
People xiaoMing = new People(20); // 使用带参数的构造函数来实例化对象
People xiaoMing2 = new People();  // ERROR：一旦显示定义了一个构造函数，就不会再生成默认的构造函数
xiaoMing.getAge(); // 打印出来的年龄变为20</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">samcyang</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;samcyang</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;532***194@qq.com</p></div></span>5年前 (2018-09-11)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-38343"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Phanio</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;pen***aw@163.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://www.cnblogs.com/xiangxinhouse/p/6277741.html">&nbsp;&nbsp;参考地址</a></p></div><div id="runoobvote-id-38343" data-commid = "38343" class="upvotejs"><a class="upvote"></a> <span class="count">27</span></div></div><div class="comt-main" id="div-comment-38343"><p data-title="CMD 编译 Java 源文件时出现的编码 GBK 的不可映射字符的错误"><strong>错误：</strong> CMD 编译 Java 源文件时出现的编码 GBK 的不可映射字符的错误。</p>

<p><strong>办法：</strong>使用 <span class="marked">javac -encoding UTF-8  .java</span> 指定编码形式。</p>
<p><strong>原因：</strong>由于 JDK 是国际版的，在编译的时候，如果我们没有用 -encoding 参数指定 JAVA 源程序的编码格式，则 java.exe 首先获得我们才做系统默认采用的编码格式，也即在编译 JAVA 程序时，若我们不指定源程序文件的编码格式，JDK 首先获得操作系统的 file.encoding 参数（它保存的就是操作系统默认的编码格式，如 win2k，他的值为 GBK），然后 JDK 就把我们的 JAVA 源程序从 file.encoding 编码格式转化为 JAVA 内部默认的 UNICODE 格式放到内存中。之后，javac 把转换后的 UNICODE 格式的文件进行编译成 class 类文件，此时 .class 文件是 UNICODE 编码的，它暂放在内存中，紧接着，JDK 将此以 UNICODE 编码编译后的 .class 文件保存到操作系统中形成我们见到的 .class 文件。但我们不加设置就编译时，相当于使用了参数: <span class="marked">javac -encoding gbk xx.java</span>，就会出现不兼容的情况。</p><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="../note/38343">Phanio</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Phanio</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;pen***aw@163.com</p><p><i class="fa fa-external-link" aria-hidden="true"></i> <a rel="nofollow" target="_blank" href="https://www.cnblogs.com/xiangxinhouse/p/6277741.html">&nbsp;&nbsp;参考地址</a></p></div></span>4年前 (2018-12-25)</div></div></li><!-- #comment-## -->
<li class="comment odd alt thread-odd thread-alt depth-1" id="comment-47076"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Ekko404</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;283***6790@qq.com</p></div><div id="runoobvote-id-47076" data-commid = "47076" class="upvotejs"><a class="upvote"></a> <span class="count">105</span></div></div><div class="comt-main" id="div-comment-47076"><p><strong>类：</strong></p> 

<pre>class A{}  //最简单的类，没有任何属性和行为</pre>
<p>一个类可以包含以下类型变量：</p>
<ul><li>
局部变量：在方法、构造方法或者语句块中定义的变量被称为局部变量。变量声明和初始化都是在方法中，方法结束后，变量就会自动销毁。</li><li>
成员变量：成员变量是定义在类中，方法体之外的变量。这种变量在创建对象的时候实例化。成员变量可以被类中方法、构造方法和特定类的语句块访问。</li><li>
类变量：类变量也声明在类中，方法体之外，但必须声明为static类型。</li></ul>
<p>一个类可以拥有多个方法，在上面的例子中：eat()、run() 和 sleep() 等都是 Dog 类的方法。</p>

<p><strong>创建对象：</strong></p>
<ul><li>
声明：声明一个对象，包括对象名称和对象类型。</li><li>
实例化：使用关键字new来创建一个对象。</li><li>
初始化：使用new创建对象时，会调用构造方法初始化对象。
</li></ul>
<p><strong>对象：</strong></p>
<p>用类名和 new 声明:</p>

<pre>A obj = new A();
A obj1 = A(); 
A obj2 = new A();</pre>


<p><strong>构造方法（构造函数）</strong></p>
<p>在创建类的里面用:</p>  
<pre>public 类名(){}  
public 类名(String name){}</pre>

<p><strong>访问实例变量和方法</strong></p>

<p>通过已创建的对象来访问成员变量和成员方法，如下所示：</p>

<pre>/* 实例化对象 */
Object referenceVariable = new Constructor();
/* 访问类中的变量 */
referenceVariable.variableName;
/* 访问类中的方法 */
referenceVariable.methodName();</pre>



<p><strong>类变量类型：</strong></p>

<p>1.局部变量：在方法、构造方法、语句块中定义的变量。其声明和初始化在方法中实现，在方法结束后自动销毁。</p>

<pre>public class  ClassName{
    public void printNumber（）{
        int a;
    }
    // 其他代码
}</pre>
<p>2.成员变量：定义在类中，方法体之外。变量在创建对象时实例化。成员变量可被类中的方法、构造方法以及特定类的语句块访问。</p>

<pre>public class  ClassName{
    int a;
    public void printNumber（）{
        // 其他代码
    }
}</pre>
<p>3.类变量：定义在类中，方法体之外，但必须要有 static 来声明变量类型。静态成员属于整个类，可通过对象名或类名来调用。</p>

<pre>public class  ClassName{
    static int a;
    public void printNumber（）{
        // 其他代码
    }
}</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">Ekko404</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;Ekko404</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;283***6790@qq.com</p></div></span>4年前 (2019-09-26)</div></div></li><!-- #comment-## -->
<li class="comment even thread-even depth-1" id="comment-47546"><span class="comt-f">#0</span><div class="comt-avatar wrapper"><i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i><div class="tooltip"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;jidaojiuyou</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;232***1805@qq.com</p></div><div id="runoobvote-id-47546" data-commid = "47546" class="upvotejs"><a class="upvote"></a> <span class="count">356</span></div></div><div class="comt-main" id="div-comment-47546"><p>简单说下类和对象。</p>
<p>以 LOL 为例。</p>

<p>首先，比如 lol 中的英雄，它就是一个类。因为所有的英雄都有对应的属性。例如：</p>

<pre>public class Hero {
    String name; //名字
    int attackDamage; //物理攻击
    int abilityPower; //法术强度
    int armor; //护甲
    int magicResistance; //魔抗
    float attackSpeed; //攻击速度
    int cooldownReduction; //冷却缩减
    int criticalStrike; //暴击率
    int moveSpeed; //移动速度
    int hp; //血量
    int mp; //蓝量
}</pre>
<p>除了属性，英雄还有行为。比如拆塔，坑队友，K头，跳舞等。</p>

<pre>public class Hero {
    public void DestroyTower(){
        System.out.println("正在拆塔");
    }
    public void Keng(){
        System.out.println("坑了一下队友");
    }
    public void Kb(){
        System.out.println("抢到了一个人头");
    }
    public void Dance(){
        System.out.println("正在跳舞");
    }
}</pre>
<p>对象就是指具体的英雄，比如德玛(garen)。就可以在 main 方法中 new 一个对象。</p>

<pre>public static void main(String[] args) {
    Hero garen = new Hero();
    garen.name = "盖伦";
    garen.attackDamage = 71;
    garen.abilityPower = 0;
    garen.armor = 36;
    garen.magicResistance = 32;
    garen.attackSpeed = 0.69f;
    garen.cooldownReduction = 0;
    garen.criticalStrike = 0;
    garen.moveSpeed = 350;
    garen.hp = 600;
    garen.mp = 0;
}</pre><div class="comt-meta wrapper"><span class="comt-author"><a target="_blank" href="javascript:;">jidaojiuyou</a><div class="tooltip tooltip1"><p><i class="fa fa-user" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;jidaojiuyou</p><p><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp;&nbsp;232***1805@qq.com</p></div></span>4年前 (2019-10-15)</div></div></li><!-- #comment-## -->
	</ol>
	<div class="pagenav">
			</div>
</div>
<div id="respond" class="no_webshot"> 
		<div class="comment-signarea" style="display:none; padding: 20px 20px;"> 
	<h3 class="text-muted" id="share_code" style="color: #799961;"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> 点我分享笔记</h3>
	<!--
	<p style="font-size:14px;">笔记需要是本篇文章的内容扩展！</p><br>
	<p style="font-size:12px;"><a href="../tougao" target="_blank">文章投稿，可点击这里</a></p>
	<p style="font-size:14px;"><a href="../w3cnote/runoob-user-test-intro.html#invite" target="_blank">注册邀请码获取方式</a></p>
		<h3 class="text-muted"><i class="fa fa-info-circle" aria-hidden="true"></i> 分享笔记前必须<a href="javascript:;" class="runoob-pop">登录</a>！</h3>
		<p><a href="../w3cnote/runoob-user-test-intro.html#invite" target="_blank">注册邀请码获取方式</a></p>-->
	</div>
		
	<form action="/wp-content/themes/runoob/option/addnote.php" method="post" id="commentform" style="display:none;">
		<div class="comt">
			<div class="comt-title">
				<i style="font-size:36px;" class="fa fa-user-circle" aria-hidden="true"></i>				<p><a id="cancel-comment-reply-link" href="javascript:;">取消</a></p>
			</div>
			<div class="comt-box">
			<div id="mded"></div>
			
				<div class="comt-ctrl">
					<div class="comt-tips"><input type='hidden' name='comment_post_ID' value='4983' id='comment_post_ID' />
<input type='hidden' name='comment_parent' id='comment_parent' value='0' />
</div>
					<button type="submit" name="submit" id="submit" tabindex="5"><i class="fa fa-pencil" aria-hidden="true"></i> 分享笔记</button>
				</div>
			</div>
		
				
					<div class="comt-comterinfo"> 
						<ul id="comment-author-info">
							<li class="form-inline"><label class="hide" for="author">昵称</label><input class="ipt" type="text" name="author" id="author" value="" tabindex="2" placeholder="昵称"><span class="text-muted">昵称 (必填)</span></li>
							<li class="form-inline"><label class="hide" for="email">邮箱</label><input class="ipt" type="text" name="email" id="email" value="" tabindex="3" placeholder="邮箱"><span class="text-muted">邮箱 (必填)</span></li>
							<li class="form-inline"><label class="hide" for="url">引用地址</label><input class="ipt" type="text" name="url" id="url" value="" tabindex="4" placeholder="引用地址"><span class="text-muted">引用地址</span></li>
						</ul>
					</div>
				
			
		</div>

	</form>
	</div>
<script type="text/javascript">
$(function() {
	//初始化编辑器
	
	var editor = new Simditor({
	  textarea: $('#mded'),
	  placeholder: '写笔记...',
	  upload:false,
	 // upload: {url:'/api/comment_upload_file.php',params: null,fileKey: 'upload_file',connectionCount: 1,leaveConfirm: '文件正在上传，您确定离开?'},
	  defaultImage: 'https://www.runoob.com/images/logo.png',
	  codeLanguages: '',
	  autosave: 'editor-content',
	  toolbar: [  'bold','code','ul','ol','image' ]
	});
	editor.on('selectionchanged', function() {
		$(".code-popover").hide();
	});

	// 提交数据
	$("#share_code").click(function() {
		$(".comment-signarea").hide();
		$("#commentform").show();
		
	});
	$("#user_add_note").click(function() {
		$(".comment-signarea").hide();
		$("#commentform").show();
		$('html, body').animate({
       	    scrollTop: $("#respond").offset().top
    	}, 200);
	});

	// 提交笔记
	var commentform=$('#commentform');
	commentform.prepend('<div id="comment-status" style="display:none;" ></div>');
	var statusdiv=$('#comment-status');
	
	commentform.submit(function(e){
		e.preventDefault();
		var noteContent = editor.getValue();
		// console.log(noteContent);
		noteContent = noteContent.replace(/<pre><code>/g,"<pre>");
		noteContent = noteContent.replace(/<\/code><\/pre>/g,"</pre>");
		
		// 系列化表单数据
		var comment_parent = 0;
		var is_user_logged_in = $("#is_user_logged_in").val();
		var comment_post_ID =  4983;
		var _wp_unfiltered_html_comment = $("#_wp_unfiltered_html_comment").val();
		var comment = noteContent;
		var author = $("#author").val();
		var url = $("#url").val();
		var email = $("#email").val();
		if(isBlank(author) && is_user_logged_in==0) {
			statusdiv.html('<p  class="ajax-error">请输入昵称！</p>').show();
		} else if(isBlank(email)  && is_user_logged_in==0) {
			statusdiv.html('<p  class="ajax-error">请输入邮箱！</p>').show();
		} else {
			// var formdata=commentform.serialize() + "&comment=" + noteContent ;
			// 添加状态信息
			statusdiv.html('<p>Processing...</p>').show();
			// 获取表单提交地址
			var formurl=commentform.attr('action');
			
			// 异步提交
			$.ajax({
					type: 'post',
					url: formurl,
					dataType:'json',
					data: {"comment_parent":comment_parent,"comment_post_ID":comment_post_ID, "_wp_unfiltered_html_comment":_wp_unfiltered_html_comment,"comment":comment,"url":url, "email":email,"author":author},
					error: function(XMLHttpRequest, textStatus, errorThrown){
					statusdiv.html('<p class="ajax-error" >数据不完整或表单提交太快了！</p>').show();
				},
				success: function(data, textStatus){
					if(data.errorno=="0") {
						$("#submit").prop('disabled', true);
						statusdiv.html('<p class="ajax-success" >笔记已提交审核，感谢分享笔记！</p>').show();
						alert('笔记已提交审核，感谢分享笔记！');
					}else{
						statusdiv.html('<p class="ajax-error" >'+data.msg+'</p>').show();
					}
					commentform.find('textarea[name=comment]').val('');
				}
			});
			setTimeout(function(){
		        $("#submit").prop('disabled', false);
		    }, 10*1000);
		}
		return false;

	});
	$(".comt-author").click(function() {
		href = $(this).children("a").attr("href");
		if(href.indexOf("/note/")!=-1) {
			var win = window.open(href, '_blank');
  			win.focus();
		}
	});
	$(".comt-meta span").hover(function(){
		$(this).children(".tooltip").css({ "opacity": 1, "pointer-events": "auto"});
	},function(){
		$(this).children(".tooltip").removeAttr("style");
	});
	/*
	$(".wrapper i").hover(function(){
		$(this).siblings(".tooltip").css({ "opacity": 1, "pointer-events": "auto"});
	},function(){
		$(this).siblings(".tooltip").css({ "opacity": 0, "pointer-events": "auto"});
	});
	*/
	//Upvote.create('runoobvote-id', {callback: vote_callback});
	var ajaxurl = 'https://www.runoob.com/wp-admin/admin-ajax.php';
	var callback = function(data) {
		//console.log($('#runoobvote-id').upvote('upvoted'));
		//console.log($('#runoobvote-id').upvote('downvoted'));
		//console.log(data);
		_vote_action = data.action;
		id_arr = data.id.split('-');
		um_id= id_arr[2];
		//console.log(um_id);
		
		var re = /^[1-9]+/;
		if (re.test(um_id)) { 
			var ajax_data = {
				_vote_action: _vote_action,
				action: "pinglun_zan",
				um_id: um_id,
				um_action: "ding"
			};
			//console.log(ajax_data);
			$.post(ajaxurl,ajax_data,function(status){
				//if(status.vote_num>999) {
				//	_voteHtml = '<span style="display: block; text-align: center;font-size: 20px; color: #6a737c; margin: 8px 0;">'+kFormatter(status.vote_num) +'</span>';
				//	$("#runoobvote-id-" + um_id + " .count").hide().after(_voteHtml);
				//}
				
			});
		}
	};
	if($('#comments').length && $('.upvotejs').length){
		$('.upvotejs').upvote({id: 4983, callback: callback});
	
		$.post(ajaxurl,{"action":"pinglun_zan","postid":4983},function(data){  
			$(data).each(function(key,value) {
				$("#runoobvote-id-" + value.commid + " .upvote").addClass(value.upvotejs_class);
				$("#runoobvote-id-" + value.commid + " .downvote").addClass(value.downvote_class);
				$("#runoobvote-id-" + value.commid + " .count").text(value.upvote_count);
			})
		},'json');
		
	}
	
	
});
function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}
function kFormatter(num) {
	// return num;
    return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)
}

</script>

<link rel="stylesheet" href="../0/qa.css?1.44">
<link rel="stylesheet" type="text/css" href="../0/simditor.min.css" />
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
		<div class="sidebar-box ">
				

<style>	
.responsive_ad1 { display:none; }
@media(min-width: 800px) { .responsive_ad1 {  display:block;margin:0 auto;} }
</style>
<div id="ad-336280" >

<script async src=""
     crossorigin="anonymous"></script>
<!-- 移动版 自动调整 -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-5751451760833794"
     data-ad-slot="1691338467"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
		</div>
				</div>
		
	</div>
</div>
	

<!-- 右边栏 -->
<div class="fivecol last right-column">

<style>
.sidebar-tree .double-li {
    width:300px;
}
.sidebar-tree .double-li li {
    width: 44%;
    line-height: 1.5em;
    border-bottom: 1px solid #ccc;
    float: left;
    display: inline;
}
</style>

    
        <div class="sidebar-box re-box re-box-large">
        <div class="sidebar-box recommend-here" style="margin: 0 auto;">
            <a href="javascript:void(0);" style="font-size: 16px; color:#64854c;font-weight:bold;"> <i class="fa fa-list" aria-hidden="true"></i> 分类导航</a>
        </div>
    <div class="sidebar-box sidebar-cate">
        
        <div class="sidebar-tree" >
            <ul><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> HTML / CSS</a><ul class="double-li"><li><a title="HTML 教程" href="../html/html-tutorial.html">HTML 教程</a></li><li><a title="HTML5 教程" href="../html/html5-intro.html">HTML5 教程</a></li><li><a title="CSS 教程" href="../css/css-tutorial.html">CSS 教程</a></li><li><a title="CSS3 教程" href="../css3/css3-tutorial.html">CSS3 教程</a></li><li><a title="Bootstrap3 教程" href="../bootstrap/bootstrap-tutorial.html">Bootstrap3 教程</a></li><li><a title="Bootstrap4 教程" href="../bootstrap4/bootstrap4-tutorial.html">Bootstrap4 教程</a></li><li><a title="Bootstrap5 教程" href="../bootstrap5/bootstrap5-tutorial.html">Bootstrap5 教程</a></li><li><a title="Font Awesome 教程" href="../font-awesome/fontawesome-tutorial.html">Font Awesome 教程</a></li><li><a title="Foundation 教程" href="../foundation/foundation-tutorial.html">Foundation 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> JavaScript</a><ul class="double-li"><li><a title="JavaScript 教程" href="../js/js-tutorial.html">JavaScript 教程</a></li><li><a title="HTML DOM 教程" href="../htmldom/htmldom-tutorial.html">HTML DOM 教程</a></li><li><a title="jQuery 教程" href="../jquery/jquery-tutorial.html">jQuery 教程</a></li><li><a title="AngularJS 教程" href="../angularjs/angularjs-tutorial.html">AngularJS 教程</a></li><li><a title="AngularJS2 教程" href="../angularjs2/angularjs2-tutorial.html">AngularJS2 教程</a></li><li><a title="Vue.js 教程" href="../vue2/vue-tutorial.html">Vue.js 教程</a></li><li><a title="Vue3 教程" href="../vue3/vue3-tutorial.html">Vue3 教程</a></li><li><a title="React 教程" href="../react/react-tutorial.html">React 教程</a></li><li><a title="TypeScript 教程" href="../typescript/ts-tutorial.html">TypeScript 教程</a></li><li><a title="jQuery UI 教程" href="../jqueryui/jqueryui-tutorial.html">jQuery UI 教程</a></li><li><a title="jQuery EasyUI 教程" href="../jeasyui/jqueryeasyui-tutorial.html">jQuery EasyUI 教程</a></li><li><a title="Node.js 教程" href="../nodejs/nodejs-tutorial.html">Node.js 教程</a></li><li><a title="AJAX 教程" href="../ajax/ajax-tutorial.html">AJAX 教程</a></li><li><a title="JSON 教程" href="../json/json-tutorial.html">JSON 教程</a></li><li><a title="Echarts 教程" href="../echarts/echarts-tutorial.html">Echarts 教程</a></li><li><a title="Chart.js 教程" href="../chartjs/chartjs-tutorial.html">Chart.js 教程</a></li><li><a title="Highcharts 教程" href="../highcharts/highcharts-tutorial.html">Highcharts 教程</a></li><li><a title="Google 地图 教程" href="../googleapi/google-maps-basic.html">Google 地图 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 服务端</a><ul class="double-li"><li><a title="Python 教程" href="../python3/python3-tutorial.html">Python 教程</a></li><li><a title="Python2.x 教程" href="../python/python-tutorial.html">Python2.x 教程</a></li><li><a title="Linux 教程" href="../linux/linux-tutorial.html">Linux 教程</a></li><li><a title="Docker 教程" href="../docker/docker-tutorial.html">Docker 教程</a></li><li><a title="Ruby 教程" href="../ruby/ruby-tutorial.html">Ruby 教程</a></li><li><a title="Java 教程" href="../java/java-tutorial.html">Java 教程</a></li><li><a title="C 教程" href="../c/c-tutorial.html">C 教程</a></li><li><a title="C++ 教程" href="../cplusplus/cpp-tutorial.html">C++ 教程</a></li><li><a title="Perl 教程" href="../perl/perl-tutorial.html">Perl 教程</a></li><li><a title="Servlet 教程" href="../servlet/servlet-tutorial.html">Servlet 教程</a></li><li><a title="JSP 教程" href="../jsp/jsp-tutorial.html">JSP 教程</a></li><li><a title="Lua 教程" href="../lua/lua-tutorial.html">Lua 教程</a></li><li><a title="Rust 教程" href="../rust/rust-tutorial.html">Rust 教程</a></li><li><a title="Scala 教程" href="../scala/scala-tutorial.html">Scala 教程</a></li><li><a title="Go 教程" href="../go/go-tutorial.html">Go 教程</a></li><li><a title="PHP 教程" href="../php/php-tutorial.html">PHP 教程</a></li><li><a title="数据结构与算法" href="../data-structures/data-structures-tutorial.html">数据结构与算法</a></li><li><a title="Django 教程" href="../django/django-tutorial.html">Django 教程</a></li><li><a title="Zookeeper 教程" href="../w3cnote/zookeeper-tutorial.html">Zookeeper 教程</a></li><li><a title="设计模式" href="../design-pattern/design-pattern-tutorial.html">设计模式</a></li><li><a title="正则表达式" href="../regexp/regexp-tutorial.html">正则表达式</a></li><li><a title="Maven 教程" href="../maven/maven-tutorial.html">Maven 教程</a></li><li><a title="Verilog 教程" href="../w3cnote/verilog-tutorial.html">Verilog 教程</a></li><li><a title="ASP 教程" href="../asp/asp-tutorial.html">ASP 教程</a></li><li><a title="AppML 教程" href="../appml/appml-tutorial.html">AppML 教程</a></li><li><a title="VBScript 教程" href="../vbscript/vbscript-tutorial.html">VBScript 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 数据库</a><ul class="double-li"><li><a title="SQL 教程" href="../sql/sql-tutorial.html">SQL 教程</a></li><li><a title="MySQL 教程" href="../mysql/mysql-tutorial.html">MySQL 教程</a></li><li><a title="PostgreSQL 教程" href="../postgresql/postgresql-tutorial.html">PostgreSQL 教程</a></li><li><a title="SQLite 教程" href="../sqlite/sqlite-tutorial.html">SQLite 教程</a></li><li><a title="MongoDB 教程" href="../mongodb/mongodb-tutorial.html">MongoDB 教程</a></li><li><a title="Redis 教程" href="../redis/redis-tutorial.html">Redis 教程</a></li><li><a title="Memcached 教程" href="../Memcached/Memcached-tutorial.html">Memcached 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 数据分析</a><ul class="double-li"><li><a title="Python 教程" href="../python3/python3-tutorial.html">Python 教程</a></li><li><a title="NumPy 教程" href="../numpy/numpy-tutorial.html">NumPy 教程</a></li><li><a title="Pandas 教程" href="../pandas/pandas-tutorial.html">Pandas 教程</a></li><li><a title="Matplotlib 教程" href="../matplotlib/matplotlib-tutorial.html">Matplotlib 教程</a></li><li><a title="Scipy 教程" href="../scipy/scipy-tutorial.html">Scipy 教程</a></li><li><a title="R 教程" href="../r/r-tutorial.html">R 教程</a></li><li><a title="Julia 教程" href="../julia/julia-tutorial.html">Julia 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 移动端</a><ul class="double-li"><li><a title="Android 教程" href="../w3cnote/android-tutorial-intro.html">Android 教程</a></li><li><a title="Swift 教程" href="../swift/swift-tutorial.html">Swift 教程</a></li><li><a title="jQuery Mobile 教程" href="../jquerymobile/jquerymobile-tutorial.html">jQuery Mobile 教程</a></li><li><a title="ionic 教程" href="../ionic/ionic-tutorial.html">ionic 教程</a></li><li><a title="Kotlin 教程" href="../kotlin/kotlin-tutorial.html">Kotlin 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> XML 教程</a><ul class="double-li"><li><a title="XML 教程" href="../xml/xml-tutorial.html">XML 教程</a></li><li><a title="DTD 教程" href="../dtd/dtd-tutorial.html">DTD 教程</a></li><li><a title="XML DOM 教程" href="../dom/dom-tutorial.html">XML DOM 教程</a></li><li><a title="XSLT 教程" href="../xsl/xsl-tutorial.html">XSLT 教程</a></li><li><a title="XPath 教程" href="../xpath/xpath-tutorial.html">XPath 教程</a></li><li><a title="XQuery 教程" href="../xquery/xquery-tutorial.html">XQuery 教程</a></li><li><a title="XLink 教程" href="../xlink/xlink-tutorial.html">XLink 教程</a></li><li><a title="XPointer 教程" href="../xlink/xlink-tutorial.html">XPointer 教程</a></li><li><a title="XML Schema 教程" href="../schema/schema-tutorial.html">XML Schema 教程</a></li><li><a title="XSL-FO 教程" href="../xslfo/xslfo-tutorial.html">XSL-FO 教程</a></li><li><a title="SVG 教程" href="../svg/svg-tutorial.html">SVG 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> ASP.NET</a><ul class="double-li"><li><a title="ASP.NET 教程" href="../aspnet/aspnet-tutorial.html">ASP.NET 教程</a></li><li><a title="C# 教程" href="../csharp/csharp-tutorial.html">C# 教程</a></li><li><a title="Web Pages 教程" href="../aspnet/webpages-intro.html">Web Pages 教程</a></li><li><a title="Razor 教程" href="../aspnet/razor-intro.html">Razor 教程</a></li><li><a title="MVC 教程" href="../aspnet/mvc-intro.html">MVC 教程</a></li><li><a title="Web Forms 教程" href="../aspnet/aspnet-intro.html">Web Forms 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> Web Service</a><ul class="double-li"><li><a title="Web Service 教程" href="../webservices/webservices-tutorial.html">Web Service 教程</a></li><li><a title="WSDL 教程" href="../wsdl/wsdl-tutorial.html">WSDL 教程</a></li><li><a title="SOAP 教程" href="../soap/soap-tutorial.html">SOAP 教程</a></li><li><a title="RSS 教程" href="../rss/rss-tutorial.html">RSS 教程</a></li><li><a title="RDF 教程" href="../rdf/rdf-tutorial.html">RDF 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 开发工具</a><ul class="double-li"><li><a title="Eclipse 教程" href="../eclipse/eclipse-tutorial.html">Eclipse 教程</a></li><li><a title="Git 教程" href="../git/git-tutorial.html">Git 教程</a></li><li><a title="Svn 教程" href="../svn/svn-tutorial.html">Svn 教程</a></li><li><a title="Markdown 教程" href="../markdown/md-tutorial.html">Markdown 教程</a></li></ul></li><li style="margin: 0;"><a href="javascript:void(0);" class="tit"> 网站建设</a><ul class="double-li"><li><a title="HTTP 教程" href="../http/http-tutorial.html">HTTP 教程</a></li><li><a title="网站建设指南" href="../web/web-buildingprimer.html">网站建设指南</a></li><li><a title="浏览器信息" href="../browsers/browser-information.html">浏览器信息</a></li><li><a title="网站主机教程" href="../hosting/hosting-tutorial.html">网站主机教程</a></li><li><a title="TCP/IP 教程" href="../tcpip/tcpip-tutorial.html">TCP/IP 教程</a></li><li><a title="W3C 教程" href="../w3c/w3c-tutorial.html">W3C 教程</a></li><li><a title="网站品质" href="../quality/quality-tutorial.html">网站品质</a></li></ul></li></ul>            </div>
    
    </div>
    </div>
    <br>
    
    <div class="sidebar-box re-box re-box-large">
        <div class="sidebar-box recommend-here">
            <a href="javascript:void(0);">Advertisement</a>
        </div>
        <div class="re-600160" id="sidebar-right-re">
                <script async src=""></script>
        <!-- 侧栏1 -->
        <ins class="adsbygoogle"
             style="display:inline-block;width:160px;height:600px"
             data-ad-client="ca-pub-5751451760833794"
             data-ad-slot="4106274865"></ins>
        <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
                </div>
    </div>
</div></div>

</div>

<script>
var aid = 4983;
function coll() {
	$.post( '/wp-content/themes/runoob/option/user/userinfo.php', {aid:aid, action:"collarticle", opt:'add'},function( data ) {
		if(data.error==0) {
			$("#content").find("h1:first").find("a").attr("href","javascript:void(0);");
			$("#content").find("h1:first").find("img").attr("src","http://www.runoob.com/wp-content/themes/runoob/assets/img/coll2.png").css({width:32+"px",height:32+"px"});
		}
		alert(data.msg);
	},'json');
}
</script>


<!-- 反馈对话框开始 -->
<script src=""></script>
<link rel="stylesheet" href="../0/feedback.css?1.0" />
<script type="text/javascript">
$.feedback({
    ajaxURL: '/feedback/runoob_feedback.php',
	html2canvasURL: '/wp-content/themes/runoob/assets/feedback/stable/2.0/html2canvas.js',
	onClose: function () {
         window.location.reload();
    }
});
</script>
<!-- 反馈对话框结束 -->
<button class="feedback-btn feedback-btn-gray">反馈/建议</button>
<!-- 底部 -->
<div id="footer" class="mar-t50">
   <div class="runoob-block">
    <div class="runoob cf">
     <dl>
      <dt>
       在线实例
      </dt>
      <dd>
       &middot;<a target="_blank" href="../html/html-examples.html">HTML 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../css/css-examples.html">CSS 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../js/js-examples.html">JavaScript 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../ajx/ajax-examples.html">Ajax 实例</a>
      </dd>
       <dd>
       &middot;<a target="_blank" href="../jquery/jquery-examples.html">jQuery 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../xml/xml-examples.html">XML 实例</a>
      </dd>
      <dd>
       &middot;<a target="_blank" href="../java/java-examples.html">Java 实例</a>
      </dd>
     
     </dl>
     <dl>
      <dt>
      字符集&工具
      </dt>
      <dd>
       &middot; <a target="_blank" href="../charsets/html-charsets.html">HTML 字符集设置</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="../tags/html-ascii.html">HTML ASCII 字符集</a>
      </dd>
     <dd>
       &middot; <a target="_blank" href="https://c.runoob.com/front-end/6939/">JS 混淆/加密</a>
      </dd> 
      <dd>
       &middot; <a target="_blank" href="https://c.runoob.com/front-end/6232/">PNG/JPEG 图片压缩</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="../tags/html-colorpicker.html">HTML 拾色器</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="..//c.runoob.com/front-end/53">JSON 格式化工具</a>
      </dd>
      <dd>
       &middot; <a target="_blank" href="..//c.runoob.com/front-end/6680/">随机数生成器</a>
      </dd>
     </dl>
     <dl>
      <dt>
       最新更新
      </dt>
                   <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imread.html" title="Matplotlib imread() 方法">Matplotlib imre...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imsave.html" title="Matplotlib imsave() 方法">Matplotlib imsa...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-imshow.html" title="Matplotlib imshow() 方法">Matplotlib imsh...</a>
      </dd>
              <dd>
       &middot;
      <a href="../matplotlib/matplotlib-hist.html" title="Matplotlib 直方图">Matplotlib 直方图</a>
      </dd>
              <dd>
       &middot;
      <a href="../python3/python-func-object.html" title="Python object() 函数">Python object()...</a>
      </dd>
              <dd>
       &middot;
      <a href="../python3/python-ai-draw.html" title="Python AI 绘画">Python AI 绘画</a>
      </dd>
              <dd>
       &middot;
      <a href="../w3cnote/cursor-editor.html" title="神辅助 Cursor 编辑器，加入 GPT-4 让编码更轻松！">神辅助 Cursor ...</a>
      </dd>
             </dl>
     <dl>
      <dt>
       站点信息
      </dt>
      <dd>
       &middot;
       <a target="_blank" href="mailto:admin@runoob.com" rel="external nofollow">意见反馈</a>
       </dd>
      <dd>
       &middot;
      <a target="_blank" href="../disclaimer">免责声明</a>
       </dd>
      <dd>
       &middot;
       <a target="_blank" href="../aboutus">关于我们</a>
       </dd>
      <dd>
       &middot;
      <a target="_blank" href="../archives">文章归档</a>
      </dd>
    
     </dl>
    
     <div class="search-share">
      <div class="app-download">
        <div>
         <strong>关注微信</strong>
        </div>
      </div>
      <div class="share">
      <img width="128" height="128" src="/wp-content/themes/runoob/assets/images/qrcode.png" />
       </div>
     </div>
     
    </div>
   </div>
   <div class="w-1000 copyright">
     Copyright &copy; 2013-2023    <strong><a href="../" target="_blank">菜鸟教程</a></strong>&nbsp;
    <strong><a href="../" target="_blank">runoob.com</a></strong> All Rights Reserved. 备案号：<a target="_blank" rel="nofollow" href="https://beian.miit.gov.cn/">闽ICP备15012807号-1</a>
   </div>
  </div>
  <div class="fixed-btn">
    <a class="go-top" href="javascript:void(0)" title="返回顶部"> <i class="fa fa-angle-up"></i></a>
    <a class="qrcode"  href="javascript:void(0)" title="关注我们"><i class="fa fa-qrcode"></i></a>
    <a class="writer" style="display:none" href="javascript:void(0)"   title="标记/收藏"><i class="fa fa-star" aria-hidden="true"></i></a>
    <!-- qrcode modal -->
    <div id="bottom-qrcode" class="modal panel-modal hide fade in">
      <h4>微信关注</h4>
      <div class="panel-body"><img alt="微信关注" width="128" height="128" src="/wp-content/themes/runoob/assets/images/qrcode.png"></div> 
    </div>
  </div>

 <div style="display:none;">
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-84264393-2"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-84264393-2');
</script>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?3eec0b7da6548cf07db3bc477ea905ee";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

</div>
<script>
window.jsui={
    www: 'https://www.runoob.com',
    uri: 'https://www.runoob.com/wp-content/themes/runoob'
};
</script>

<script src=""></script>
<script src=""></script>

</body>
</html>